<!--
 * 新建/编辑 积分配置
-->
<template>
  <div class="task-update-create">
    <div class="task-update-create-title">新建/编辑积分配置</div>
    <section v-loading="loading" class="task-update-create-main">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="150px"
        class="form"
      >
        <el-form-item label="配置名称" prop="configCode">
          <el-select
            v-model="form.configCode"
            placeholder="请选择配置名称"
            @change="handleSelectChange"
          >
            <el-option
              v-for="item in dict.INTEGRAL"
              :key="item.value"
              :label="item.dictName"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <!-- prop="configValue" -->
        <div
          v-if="
            form.configCode !== 'INTEGRAL_PK_SRS' &&
              form.configCode !== 'INTEGRAL_PK_SRDZ'
          "
          class="config-content"
        >
          <el-form-item label="配置值" required>
            <el-card class="box-card">
              <div v-if="form.configCode === 'INTEGRAL_SIGN_IN'">
                <el-table :data="jsonData.signData" style="width: 100%">
                  <el-table-column prop="day" label="签到天数">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.day"
                        placeholder="请输入签到天数"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="points" label="获得积分">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.points"
                        placeholder="请输入获得积分数"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="address" label="操作">
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        @click="handleDel(scope.row)"
                      >删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <section
                  v-if="jsonData.signData && jsonData.signData.length < 7"
                  class="inner-add"
                  @click="handleIconAdd()"
                >
                  添加
                </section>
              </div>
              <div v-else>
                <el-form-item
                  label="每次获取积分数量"
                  prop="configRemark"
                  style="margin-top:10px;"
                >
                  <el-input
                    v-model.trim="jsonData.points"
                    placeholder="请输入每次获取积分数量"
                  />
                </el-form-item>
                <el-form-item
                  v-if="
                    form.configCode === 'INTEGRAL_VIDEO' ||
                      form.configCode === 'INTEGRAL_AUDIO' ||
                      form.configCode === 'INTEGRAL_TOOL_RESOURCE' ||
                      form.configCode === 'INTEGRAL_EVERYDAYLISTEN'
                  "
                  label="获得积分学习时长(秒)"
                  prop="configRemark"
                  style="margin-top:10px;"
                >
                  <!--                <el-input v-model.trim="jsonData.duration" placeholder="请输入获得积分学习时长(秒)" />-->
                  <el-select
                    v-model="jsonData.duration"
                    placeholder="请输入获得积分学习时长(秒)"
                  >
                    <el-option
                      v-for="(i, n) in durationList"
                      :key="n"
                      :label="i.label"
                      :value="i.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  label="每日获得积分上限"
                  prop="configRemark"
                  style="margin-top:10px;"
                >
                  <el-input
                    v-model.trim="jsonData.erverydayMaxPoints"
                    placeholder="请输入每日获得积分上限"
                  />
                </el-form-item>
              </div>
            </el-card>
          </el-form-item>
          <el-form-item label="配置说明" prop="configRemark">
            <el-input
              v-model="form.configRemark"
              :autosize="{ minRows: 2, maxRows: 4 }"
              type="textarea"
              placeholder="请输入配置说明"
            />
          </el-form-item>
          <el-form-item label="图标" prop="taskImgId">
            <image-upload
              :key="uploadImg.imagecropperKey"
              v-model="form.taskImgId"
              :preview-id="uploadImg.viewId"
              :forever="true"
              :width="94"
              :view="uploadImg.view"
              :height="96"
              :no-circle="true"
              :no-rotate="false"
              lang-type="zh"
              :is-oss="isOss"
              @changeOssPath="
                (path) => {
                  uploadImg.viewId = path
                }
              "
            />
          </el-form-item>
          <!-- <el-form-item label="是否获取成就">
            <el-radio-group v-model="form.isGetAchievement">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item> -->
        </div>
        <div
          v-if="form.configCode === 'INTEGRAL_PK_SRS'"
          class="config-content"
        >
          <el-form-item label="配置值" required>
            <el-card class="box-card">
              <el-form-item
                v-for="(ss, ssi) in jsonData.signData"
                :key="ssi"
                :label="
                  `${ss.time == '1' ? '首局' : `第${zhNum[ss.time]}局`}第${
                    zhNum[ss.level]
                  }名获得积分数量`
                "
                prop="erverydayMaxPoints"
              >
                <el-input
                  v-model="ss.points"
                  :placeholder="`请输入第${zhNum[ss.level]}名获得积分数量`"
                />
              </el-form-item>
              <el-form-item label="每日获得积分上限" prop="erverydayMaxPoints">
                <el-input
                  v-model="jsonData.erverydayMaxPoints"
                  placeholder="请输入每日获得积分上限"
                />
              </el-form-item> </el-card></el-form-item>
          <el-form-item label="图标" prop="taskImgId">
            <image-upload
              :key="uploadImg.imagecropperKey"
              v-model="form.taskImgId"
              :preview-id="uploadImg.viewId"
              :forever="true"
              :width="94"
              :view="uploadImg.view"
              :height="96"
              :no-circle="true"
              :no-rotate="false"
              lang-type="zh"
              :is-oss="isOss"
              @changeOssPath="
                (path) => {
                  uploadImg.viewId = path
                }
              "
            />
          </el-form-item>
          <el-form-item label="配置说明" prop="configRemark">
            <tinymce
              v-if="showtinymce"
              v-model="form.configRemark"
              :is-oss="isOss"
              :height="300"
              placeholder="请输入配置说明"
            />
          </el-form-item>
        </div>
        <div
          v-if="form.configCode === 'INTEGRAL_PK_SRDZ'"
          class="config-content"
        >
          <el-form-item label="配置值" required>
            <el-card class="box-card">
              <el-form-item
                v-for="(ss, ssi) in jsonData.signData"
                :key="ssi"
                :label="`第${zhNum[ss.level]}名获得积分数量`"
                prop="erverydayMaxPoints"
              >
                <el-input
                  v-model="ss.points"
                  :placeholder="`请输入第${zhNum[ss.level]}名获得积分数量`"
                />
              </el-form-item>
              <el-form-item label="每日获得积分上限" prop="erverydayMaxPoints">
                <el-input
                  v-model="jsonData.erverydayMaxPoints"
                  placeholder="请输入每日获得积分上限"
                />
              </el-form-item> </el-card></el-form-item>
          <el-form-item label="图标" prop="taskImgId">
            <image-upload
              :key="uploadImg.imagecropperKey"
              v-model="form.taskImgId"
              :preview-id="uploadImg.viewId"
              :forever="true"
              :width="94"
              :view="uploadImg.view"
              :height="96"
              :no-circle="true"
              :no-rotate="false"
              lang-type="zh"
              :is-oss="isOss"
              @changeOssPath="
                (path) => {
                  uploadImg.viewId = path
                }
              "
            />
          </el-form-item>
          <el-form-item label="配置说明" prop="configRemark">
            <tinymce
              v-if="showtinymce"
              v-model="form.configRemark"
              :is-oss="isOss"
              :height="300"
              placeholder="请输入配置说明"
            />
          </el-form-item>
        </div>
        <el-form-item label="链接类型">
          <el-radio-group v-model="form.linkType">
            <el-radio :label="0">无</el-radio>
            <el-radio :label="1">内部链接</el-radio>
            <el-radio :label="2">外部链接</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="form.linkType !== 0"
          label="跳转地址"
          prop="linkAddress"
        >
          <el-input v-model="form.linkAddress" placeholder="请输入跳转地址" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input
            v-model.number="form.sort"
            placeholder="请输入排序号（值越大，越靠前）"
            maxlength="10"
          />
        </el-form-item>
      </el-form>
    </section>
    <section class="task-update-create-footer">
      <el-button
        style="padding: 10px 30px;"
        @click="handleCancel"
      >取 消</el-button>
      <el-button type="primary" @click="handleSubmit('form')">确 定</el-button>
    </section>
  </div>
</template>

<script>
import { allowEmptyNumber } from '@/utils/validate'
import { insert, updateAll, getAll, getDictByCode } from '../api'
import imageUpload from '@/components/ImageUpload'
import Tinymce from '@/components/Tinymce'

export default {
  name: 'TaskUpdate',
  components: { imageUpload, Tinymce },
  data() {
    return {
      loading: false,
      form: {
        id: '',
        configCode: '',
        sort: '',
        configRemark: '',
        configValue: '',
        taskImgId: '', // 默认图
        linkType: 0,
        linkAddress: '',
        status: 'ZT01', // 默认禁用,
        startTime: '',
        endTime: '',
        // isGetAchievement: 0
      },
      defaultImgPath: '', // 默认图的oss地址
      rules: {
        configCode: [
          { required: true, message: '请输入配置标识', trigger: 'blur' }
        ],
        configValue: [
          { required: true, message: '请输入配置值', trigger: 'blur' }
        ],
        sort: [
          { required: false, validator: allowEmptyNumber, trigger: 'blur' }
        ],
        linkAddress: [
          { required: true, message: '请输入跳转地址', trigger: 'blur' }
        ],
        taskImgId: [
          { required: true, message: '请上传图标', trigger: 'change' }
        ]
      },
      state: '',
      dict: {
        INTEGRAL: []
      },
      isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false,
      uploadImg: {
        viewId: '',
        view: '',
        imagecropperKey: 0
      },
      jsonData: {
        signData: [],
        points: '',
        erverydayMaxPoints: '',
        duration: '',
        failPoints: '0'
      },
      durationList: [
        { value: '0', label: '0秒' },
        { value: '30', label: '30秒' },
        { value: '60', label: '60秒' },
        { value: '120', label: '120秒' },
        { value: '180', label: '180秒' },
        { value: '300', label: '300秒' }
      ],
      zhNum: ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'],
      showtinymce: false
    }
  },
  async created() {
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    for (const i in this.dict) {
      await this.getDict(i)
    }
    if (this.$route.query.type === 'u') {
      if (!this.$route.query.i) {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.handleCancel()
          }
        })
      } else {
        this.getData(this.$route.query.i)
      }
    } else {
      this.showtinymce = true
    }
  },
  methods: {
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode({ dictCode: code })
          .then((res) => {
            this.dict[code] =
              res.data.data && res.data.data.length > 0
                ? res.data.data[0].list
                : []
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    /**
     * 返回
     */
    handleCancel() {
      this.$router.back()
    },
    handleSubmit() {
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            params.configValue = JSON.stringify(this.jsonData)
            return new Promise((resolve, reject) => {
              insert(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.handleCancel()
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            params.configValue = JSON.stringify(this.jsonData)
            return new Promise((resolve, reject) => {
              updateAll(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '修改成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.handleCancel()
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            return false
          }
        })
      }
    },
    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getAll({ id: id })
          .then((res) => {
            loading.close()
            const data = res.data.data
            for (const key in this.form) {
              this.form[key] = data[key]
            }
            this.uploadImg.viewId = data.taskImgUrl
            this.jsonData = data.configValue && JSON.parse(data.configValue)
            this.showtinymce = true
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },
    handleIconAdd() {
      if (this.jsonData.signData.length < 7) {
        this.jsonData.signData.push({
          day: '',
          points: '',
          type: '1'
        })
      } else {
        this.$message({
          type: 'warning',
          message: '最多只能添加7条签到'
        })
      }
    },
    handleDel(row) {
      if (this.jsonData.signData.length > 0 && row) {
        this.jsonData.signData.splice(row.$index, 1)
      }
    },
    handleSelectChange(val) {
      this.dict.INTEGRAL.forEach((element) => {
        if (element.dictValue === val) {
          this.form.configName = element.dictName
        }
      })
      if (val === 'INTEGRAL_PK_SRDZ') {
        this.jsonData.signData = [
          { time: '1', level: '1', points: '', type: '1' },
          { time: '1', level: '2', points: '', type: '1' }
        ]
      } else if (val === 'INTEGRAL_PK_SRS') {
        this.jsonData.signData = [
          { time: '1', level: '1', points: '', type: '1' },
          { time: '1', level: '2', points: '', type: '1' },
          { time: '1', level: '3', points: '', type: '1' },
          { time: '1', level: '4', points: '', type: '1' },
          { time: '2', level: '1', points: '', type: '1' },
          { time: '2', level: '2', points: '', type: '1' },
          { time: '2', level: '3', points: '', type: '1' },
          { time: '2', level: '4', points: '', type: '1' }
        ]
      } else {
        this.jsonData.signData = []
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.task-update-create {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .task-update-create-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .task-update-create-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;

    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    &:hover {
      overflow: auto;
    }

    .form {
      width: 1000px !important;
      margin: 0 auto;

      .el-select {
        width: 100%;
      }

      .line {
        text-align: center;
      }
    }

    .select-btn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
      margin-bottom: 10px;
    }
  }

  .task-update-create-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }

  .inner-add {
    cursor: pointer;
    line-height: 40px;
    text-align: center;
    border: 1px dotted #e5e5e5;

    &:hover {
      @include font-color($mainColor);
      @include border-color(1px, dotted, $mainColor);
    }
  }
}
</style>
